package com.xxxy.jsq.action.course;

import com.alibaba.fastjson2.JSONObject;
import com.xxxy.jsq.dao.CourseDao;
import com.xxxy.jsq.model.Course;
import com.xxxy.jsq.model.Page;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class getAllCoursesPageServlet
 */
@WebServlet("/getAllCoursesPageServlet")
public class getAllCoursesPageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public getAllCoursesPageServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Course model = new Course();
        CourseDao dao = new CourseDao();

        // 获取查询条件
        String courseName = request.getParameter("courseName");
        String courseNum = request.getParameter("courseNum");
        String courseFlag = request.getParameter("courseFlag");

        if (courseName != null && !courseName.equals("")) {
            model.setCourseName(courseName);
        }
        if (courseNum != null && !courseNum.equals("")) {
            model.setCourseNum(courseNum);
        }
        if (courseFlag != null && !courseFlag.equals("")) {
            model.setCourseFlag(courseFlag);
        }

        // 获取分页参数
        String cpage = request.getParameter("page");
        String limit = request.getParameter("limit");
        Page page = new Page();

        if (cpage != null && !cpage.equals("")) {
            page.setCurrentPage(Integer.parseInt(cpage));
            page.setCount(Integer.parseInt(limit));
        }

        // 查询分页数据
        List<Course> list = dao.getAllDataByPage(model, page);
        int total = dao.getCount(model); // 获取记录总数

        // 构建JSON响应
        JSONObject jo = new JSONObject();
        jo.put("code", 0);
        jo.put("msg", "查询成功");
        jo.put("count", total);
        jo.put("data", list);

        // 返回响应
        PrintWriter out = response.getWriter();
        out.print(jo.toString());
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}